<template>
  <a-layout-content class="chat-panel">
    <a-layout-header class="chat-header">
      <span class="chat-title">
        {{ chatInfo.nickname }}
      </span>
    </a-layout-header>

    <div class="chat-messages" ref="messagesContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message"
        :class="{ 'message-self': message.senderId === currentUserId }"
      >
        <a-avatar
          :src="
            message.senderId === currentUserId
              ? authStore.user?.avatar
              : chatInfo.avatar
          "
        />
        <div class="message-wrapper">
          <div class="message-content" v-html="renderMessage(message)"></div>
          <div class="message-time">{{ formatTime(message.createTime) }}</div>
        </div>
      </div>
    </div>

    <div class="chat-input-area">
      <div class="chat-toolbar">
        <EmojiPicker @select="insertEmoji" />
        <paper-clip-outlined class="toolbar-icon" @click="handleFileClick" />
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          @change="handleFileSelect"
        />
        <picture-outlined class="toolbar-icon" />
      </div>

      <a-textarea
        v-model:value="inputMessage"
        :rows="4"
        placeholder="输入消息..."
        class="chat-input"
        @keyup.enter.exact="sendMessage"
      />
      <a-button type="primary" class="send-button" @click="sendMessage">
        发送
      </a-button>
    </div>
  </a-layout-content>
</template>

<script lang="ts" setup>
import {
  ref,
  onMounted,
  onUnmounted,
  defineProps,
  nextTick,
  computed,
  watch,
} from "vue";
import {
  SmileOutlined,
  PictureOutlined,
  PaperClipOutlined,
  FileOutlined,
} from "@ant-design/icons-vue";
import { Contact } from "@/types/contact";
import { useAuthStore } from "@/store/auth";
import { wsClient } from "@/util/websocket";
import {
  PrivateMessage,
  MessageType,
  MessageStatus,
  ReadStatus,
  ContentType,
} from "@/types/message";
import { message } from "ant-design-vue";
import {
  getPrivateMessageHistory,
  markMessagesAsRead,
  uploadFile,
} from "@/api/message";
import dayjs from "dayjs";
import EmojiPicker from "./EmojiPicker.vue";
import { FILE_BASE_URL, API_BASE_URL } from "@/config";

interface Props {
  chatInfo: Contact;
}

const props = defineProps<Props>();
const inputMessage = ref("");
const authStore = useAuthStore();
const messages = ref<PrivateMessage[]>([]);
const messagesContainer = ref<HTMLElement | null>(null);
const fileInput = ref<HTMLInputElement | null>(null);

const currentUserId = computed(() => authStore.user?.id);

// 先定义 loadHistoryMessages 函数
const loadHistoryMessages = async () => {
  try {
    if (!authStore.user?.id || !props.chatInfo.friendId) return;

    console.log("Loading messages for contact:", props.chatInfo);

    const response = await getPrivateMessageHistory(
      authStore.user.id,
      props.chatInfo.friendId
    );

    if (response.data.code === 200) {
      // 处理历史消息中的文件消息
      // 处理历史消息中的文件消息
      messages.value = response.data.data.map((msg: PrivateMessage) => {
        if (msg.messageType === 3) {
          console.info("History file message:", msg);
          return {
            ...msg,
            // 使用数据库中存储的文件名和大小
            fileName: msg.fileName || "未知文件",
            fileSize: msg.fileSize || 0,
          };
        }
        return msg;
      });
      scrollToBottom();
      // 标记消息为已读
      await markMessagesAsRead(authStore.user.id, props.chatInfo.friendId);
    }
  } catch (error) {
    console.error("加载历史消息失败:", error);
    message.error("加载历史消息失败");
  }
};

// 其他辅助函数
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

const formatTime = (time: string | undefined) => {
  if (!time) return "";
  return dayjs(time).format("HH:mm");
};

// 然后再定义 watch
watch(
  () => props.chatInfo,
  async (newContact) => {
    if (newContact) {
      messages.value = []; // 清空当前消息
      await loadHistoryMessages(); // 加载新的聊天记录
    }
  },
  { immediate: true }
);

// 处理收到的消息
const handleMessage = (msg: PrivateMessage) => {
  if (!msg) return;
  const isCurrentChat =
    msg.senderId === props.chatInfo.friendId ||
    msg.receiverId === props.chatInfo.friendId;

  if (isCurrentChat) {
    // 如果是文件消息，确保所有必要的字段都存在
    if (msg.type === ContentType.FILE) {
      msg = {
        ...msg,
        fileName: extractFileName(msg.content) || "未知文件",
        fileSize: msg.fileSize || 0,
      };
    }

    messages.value.push(msg);
    scrollToBottom();
  }
};

// 添加提取文件名的辅助函数
const extractFileName = (content: string) => {
  if (!content) return null;
  const urlParts = content.split("/");
  return decodeURIComponent(urlParts[urlParts.length - 1]);
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return;

  if (!props.chatInfo || !currentUserId.value) {
    message.error("发送失败：无效的聊天信息");
    return;
  }

  const msg: PrivateMessage = {
    id: Date.now(),
    senderId: currentUserId.value,
    receiverId: props.chatInfo.friendId,
    content: inputMessage.value,
    messageType: MessageType.PRIVATE,
    contentType: ContentType.TEXT,
    status: MessageStatus.SENT,
    readStatus: ReadStatus.UNREAD,
    createTime: new Date().toISOString(),
  };

  try {
    // 调用 WebSocketClient 的 sendMessage 方法发送消息
    wsClient.sendMessage(msg);
    // 将发送的消息添加到聊天面板
    messages.value.push(msg);
    // 清空聊天输入框
    inputMessage.value = "";
    scrollToBottom();
  } catch (error) {
    message.error("发送失败，请重试");
    console.error("发送消息失败:", error);
  }
};

// 修改 onMounted
onMounted(() => {
  wsClient.addMessageHandler(MessageType.PRIVATE, handleMessage);
});

onUnmounted(() => {
  console.log("Removing message handler for type:", MessageType.PRIVATE);
  wsClient.removeMessageHandler(MessageType.PRIVATE, handleMessage);
});

const insertEmoji = (emoji: string) => {
  inputMessage.value += emoji;
};

const handleFileClick = () => {
  fileInput.value?.click();
};

const handleFileSelect = async (event: Event) => {
  const files = (event.target as HTMLInputElement).files;
  if (!files || files.length === 0) return;

  const file = files[0];
  const maxSize = 10 * 1024 * 1024;

  if (file.size > maxSize) {
    message.error("文件大小不能超过10MB");
    return;
  }

  try {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("senderId", currentUserId.value!.toString());
    formData.append("receiverId", props.chatInfo.friendId.toString());
    formData.append("messageType", MessageType.PRIVATE.toString());

    const response = await uploadFile(formData, MessageType.PRIVATE);
    const result = response.data;

    if (result.code === 200) {
      // 构建文件消息
      const msg: PrivateMessage = {
        senderId: currentUserId.value!,
        receiverId: props.chatInfo.friendId,
        content: result.data.url,
        messageType: MessageType.PRIVATE,
        contentType: ContentType.FILE,
        status: MessageStatus.SENT,
        readStatus: ReadStatus.UNREAD,
        createTime: new Date().toISOString(),
        fileName: file.name,
        fileSize: file.size,
      };

      console.log("Sending file message:", msg);
      wsClient.sendMessage(msg);
      messages.value.push(msg);
      scrollToBottom();
    }
  } catch (error) {
    message.error("文件发送失败");
    console.error("文件发送失败:", error);
  } finally {
    // 清空文件输入框
    if (fileInput.value) {
      fileInput.value.value = "";
    }
  }
};

// 渲染文件消息
const renderMessage = (msg: PrivateMessage) => {
  if (msg.messageType === 3) {
    console.log("Rendering file message:", msg);
    const fileUrl = `${API_BASE_URL}/file${msg.content}`;
    const fileName = msg.fileName || extractFileName(msg.content) || "未知文件";
    const fileSize = msg.fileSize ? formatFileSize(msg.fileSize) : "未知大小";

    // 获取文件扩展名
    const fileExt = fileName.split(".").pop()?.toLowerCase() || "";

    // 根据文件类型选择图标
    let fileIcon = "file";
    if (["jpg", "jpeg", "png", "gif"].includes(fileExt)) {
      fileIcon = "file-image";
    } else if (["doc", "docx"].includes(fileExt)) {
      fileIcon = "file-word";
    } else if (["xls", "xlsx"].includes(fileExt)) {
      fileIcon = "file-excel";
    } else if (["pdf"].includes(fileExt)) {
      fileIcon = "file-pdf";
    } else if (["txt"].includes(fileExt)) {
      fileIcon = "file-text";
    }

    return `
      <a href="${fileUrl}" class="file-message-wrapper" target="_blank" download="${fileName}">
        <div class="file-icon">
          <i class="anticon anticon-${fileIcon}"></i>
          <span class="file-ext">${fileExt.toUpperCase()}</span>
        </div>
        <div class="file-info">
          <div class="file-name" title="${fileName}">${fileName}</div>
          <div class="file-size">${fileSize}</div>
        </div>
        <div class="download-button">
          <i class="anticon anticon-download"></i>
        </div>
      </a>
    `;
  }
  return msg.content;
};

const downloadFile = (url: string) => {
  window.open(url, "_blank");
};

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return "未知大小";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};
</script>

<style scoped>
.chat-panel {
  display: flex;
  flex-direction: column;
  background: #fff;
  height: 100%;
}

.chat-header {
  height: 64px;
  line-height: 64px;
  padding: 0 24px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.chat-title {
  font-size: 16px;
  font-weight: 500;
}

.member-count {
  font-size: 14px;
  color: #999;
  margin-left: 8px;
}

.chat-messages {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: #f5f5f5;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 24px;
  gap: 12px;
}

.message-self {
  flex-direction: row-reverse;
}

.message-wrapper {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-sender {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.message-content {
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  word-break: break-all;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  display: inline-block;
  max-width: 100%;
}

.message-self .message-content {
  background: #1890ff;
  color: #fff;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.chat-input-area {
  padding: 16px 24px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  position: relative;
}

.chat-toolbar {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
  color: #595959;
}

.toolbar-icon {
  font-size: 20px;
  cursor: pointer;
  transition: color 0.3s;
}

.toolbar-icon:hover {
  color: #1890ff;
}

.chat-input {
  margin-bottom: 12px;
  resize: none;
  border-radius: 4px;
}

.chat-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.send-button {
  float: right;
  height: 32px;
  padding: 0 16px;
}

.emoji-picker {
  position: absolute;
  bottom: 200px;
  left: 24px;
  width: 300px;
  height: 200px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f5f5f5;
}

/* 头像样式 */
.message :deep(.ant-avatar) {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  flex-shrink: 0;
}

/* 输入框样式 */
.chat-input-area :deep(.ant-input) {
  border-radius: 4px;
  resize: none;
}

/* 按钮样式 */
.chat-input-area :deep(.ant-btn) {
  border-radius: 4px;
}

/* 确保表情选择器和其他图标齐 */
:deep(.emoji-picker) {
  display: flex;
  align-items: center;
}

/* 添加文件消息样式 */
.file-message {
  display: flex;
  align-items: center;
  padding: 8px;
  background-color: #f0f2f5;
  border-radius: 4px;
  cursor: pointer;
  max-width: 300px;
  word-break: break-all;
}

.file-message:hover {
  background-color: #e6e8eb;
}

.file-icon {
  font-size: 24px;
  margin-right: 8px;
  color: #1890ff;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 12px;
  color: #8c8c8c;
}

/* 文件消息样式 */
.file-message-wrapper {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 12px;
  max-width: 320px;
  transition: all 0.3s ease;
  text-decoration: none;
}

.message-self .file-message-wrapper {
  background: #1890ff;
  border-color: #1890ff;
}

.file-message-wrapper:hover {
  background: #fff;
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-decoration: none;
}

.file-icon {
  position: relative;
  width: 40px;
  height: 40px;
  background: #e6f7ff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.file-icon .anticon {
  font-size: 20px;
  color: #1890ff;
}

.file-ext {
  position: absolute;
  bottom: -2px;
  font-size: 8px;
  background: #1890ff;
  color: white;
  padding: 1px 4px;
  border-radius: 4px;
  text-transform: uppercase;
}

.message-self .file-ext {
  background: #fff;
  color: #1890ff;
}

.file-info {
  flex: 1;
  min-width: 0;
  margin-right: 12px;
}

.file-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.message-self .file-name {
  color: #fff;
}

.file-size {
  font-size: 12px;
  color: #666;
}

.message-self .file-size {
  color: rgba(255, 255, 255, 0.85);
}

.download-button {
  width: 32px;
  height: 32px;
  background: #1890ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.message-self .download-button {
  background: #fff;
}

.message-self .download-button .anticon {
  color: #1890ff;
}

.download-button:hover {
  background: #40a9ff;
  transform: scale(1.1);
}

.message-self .download-button:hover {
  background: #f0f0f0;
}

.download-button .anticon {
  font-size: 16px;
  color: white;
}

/* 确保消息内容区域可以容纳文件消息 */
.message-content:has(.file-message-wrapper) {
  min-width: 240px;
  max-width: 400px;
}

/* 调整自己发送的文件消息样式 */
.message-self .file-icon {
  background: rgba(255, 255, 255, 0.9);
}

.message-self .file-icon .anticon {
  color: #1890ff;
}
</style>
